package com.orangelife.webservice.service.propApp.impl;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.springframework.stereotype.Service;

import com.orangelife.exception.AppBizException;
import com.orangelife.redis.core.redis.session.redisSession.WebServiceSession;
import com.orangelife.service.feeDetail.IFeeDetailService;
import com.orangelife.service.propApp.IPropAppService;
import com.orangelife.service.propApp.IPropFeeMemberApartmentService;
import com.orangelife.service.propApp.model.PropFeeMemberApartment;
import com.orangelife.service.property.PropCollectionService;
import com.orangelife.setting.constant.CodeConst;
import com.orangelife.setting.constant.InfoConst;
import com.orangelife.utils.StringUtils;
import com.orangelife.webservice.base.BaseService;
import com.orangelife.webservice.service.paybill.entity.PayBillDto;
import com.orangelife.webservice.service.propApp.IPropAppWebService;
import com.orangelife.webservice.service.propApp.util.ContentComparator;

@Service("PropAppWebService")
public class PropAppWebServiceImpl extends BaseService implements
		IPropAppWebService {

	@Resource(name = "propFeeMemberApartmentService")
	private IPropFeeMemberApartmentService propFeeMemberApartmentService;
	@Resource(name = "propCollectionService")
	private PropCollectionService propCollectionService;

	@Resource(name = "propAppService")
	private IPropAppService propAppService;
	@Resource(name = "feeDetailService")
	private IFeeDetailService feeDetailService;

	@Override
	public Response FeeDetailForApp(HttpServletRequest request,
			String apartmentID, String commID, String type,String otherName, String isPre)
			throws AppBizException {

		if (StringUtils.isBlank(apartmentID)) {
			return this.abnormalResp(100002, "房屋ID不能为空");
		}

		if (StringUtils.isBlank(commID)) {
			return this.abnormalResp(100002, "小区ID不能为空");
		}
    //转化utf-8房号别名
		try {
			if(otherName!=null && otherName!="" ){
				otherName=java.net.URLDecoder.decode(otherName,"utf-8");

			}
		}catch (UnsupportedEncodingException e){

		}

		List<Map<String, Object>> baseinfolist = new ArrayList<Map<String, Object>>();

		baseinfolist = propAppService.selectProInfo2(apartmentID,otherName);

		if (baseinfolist.size() == 0) {
			return this.abnormalResp(100009, "房屋未开通该服务");
		}

		Map<String, Object> baseinfomap = baseinfolist.get(0);
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		list = propCollectionService.getPayBillInfoGroupForApp(apartmentID,
				isPre);

		BigDecimal totalamount = BigDecimal.ZERO;

		Map<String, List<Map<String, Object>>> tempmap = new TreeMap<String, List<Map<String, Object>>>();

		for (Map<String, Object> map : list) {

			BigDecimal amount = (BigDecimal) map.get("sumamount");

			totalamount = totalamount.add(amount);
			String date = (String) map.get("date");
			if (tempmap.get(date) == null) {
				List<Map<String, Object>> templist = new ArrayList<Map<String, Object>>();
				templist.add(map);
				tempmap.put(date, templist);

			} else {
				tempmap.get(date).add(map);
			}

		}

		TreeSet<String> keyset = new TreeSet<>(tempmap.keySet());

		List<Map<String, Object>> lmm = new ArrayList<Map<String, Object>>();
		Map<String, Map<String, Object>> year = new HashMap<String, Map<String, Object>>();
		String y = null;
		if ("1".equals(type)) {
			for (String string : keyset) {

				Map<String, Object> mm = new TreeMap<String, Object>();
				mm.put("month", string.split("-")[1] + "月");
				mm.put("feeDetails", tempmap.get(string));
				List<Map<String, Object>> llm = tempmap.get(string);
				BigDecimal monthtotal = BigDecimal.ZERO;
				List<String> idlist = new ArrayList<String>();
				for (Map<String, Object> tmap : llm) {
					BigDecimal b = (BigDecimal) tmap.get("sumamount");

					String idarray = (String) tmap.get("idarray");
					String[] ids = idarray.split(",");
					for (String id : ids) {
						idlist.add(id);

					}
					tmap.remove("idarray");
					monthtotal = monthtotal.add(b);

				}

				mm.put("mtotal", monthtotal);
				mm.put("feeDetailIDs", idlist);

				y = string.substring(0, 4);

				Map<String, Object> mmm = year.get(y);
				if (mmm == null) {

					mmm = new HashMap<String, Object>();
					mmm.put("year", y);
					mmm.put("ytotal", BigDecimal.ZERO);
					mmm.put("yearInfo", new ArrayList<Object>());
					year.put(y, mmm);

					lmm.add(mmm);
				}

				mmm.put("ytotal", new BigDecimal(mm.get("mtotal").toString())
						.add((BigDecimal) mmm.get("ytotal")));
				List l1 = (List) mmm.get("yearInfo");

				l1.add(mm);

			}

		} else {

			for (String string : keyset) {
				Map<String, Object> mm = new TreeMap<String, Object>();
				mm.put("date", string);
				mm.put("subitem", tempmap.get(string));
				List<Map<String, Object>> llm = tempmap.get(string);
				BigDecimal monthtotal = BigDecimal.ZERO;
				List<String> idlist = new ArrayList<String>();
				for (Map<String, Object> tmap : llm) {
					BigDecimal b = (BigDecimal) tmap.get("sumamount");

					String idarray = (String) tmap.get("idarray");
					String[] ids = idarray.split(",");
					for (String id : ids) {
						idlist.add(id);

					}
					tmap.remove("idarray");
					monthtotal = monthtotal.add(b);

				}

				mm.put("monthtotal", monthtotal);
				mm.put("ids", idlist);

				lmm.add(mm);

			}
		}

		Map<String, Object> map = new HashMap<String, Object>();
		// map.put("type", type);
		map.put("apartmentID", apartmentID);
		map.put("commID", commID);

		String building_name = (String) baseinfomap.get("building_name");
		String unit_name = (String) baseinfomap.get("unit_name");
		String apartment_num = (String) baseinfomap.get("apartment_num");
		String comm = (String) baseinfomap.get("comm");
		String fee_area = StringUtils.toString(baseinfomap.get("fee_area"), "");
		Map<String, Object> qmap1 = new HashMap<String, Object>();
		List<Map<String, Object>> baseInfo = new ArrayList<Map<String, Object>>();
		qmap1.put("name", "小区名称");
		qmap1.put("value", comm);
		Map<String, Object> qmap2 = new HashMap<String, Object>();
		qmap2.put("name", "房屋信息");
		qmap2.put("value",
				building_name
						+ "-"
						+ (StringUtils.isBlank(unit_name) ? ""
								: (unit_name + "-")) + apartment_num);
		Map<String, Object> qmap3 = new HashMap<String, Object>();
		qmap3.put("name", "房屋面积");
		qmap3.put("value", fee_area + "㎡");
		Map<String, Object> qmap4 = new HashMap<String, Object>();
		baseInfo.add(qmap1);
		baseInfo.add(qmap2);
		baseInfo.add(qmap3);
		if (!(keyset.size() == 0 || keyset == null)) {
			qmap4.put("name", "应缴期间");
			qmap4.put("value", keyset.first() + "至" + keyset.last());
			baseInfo.add(qmap4);
		} else {
			qmap4.put("name", "应缴期间");
			qmap4.put("value", "无");
			baseInfo.add(qmap4);
		}

		map.put("totalamount", totalamount);
		map.put("baseInfo", baseInfo);
		map.put("orderInfo", lmm);

		return normalResp(map);
	}

	@Override
	public Response FeeListForApp(HttpServletRequest request, String commID)
			throws AppBizException {
		/*
		 * if (StringUtils.isBlank(commID)) { return this.abnormalResp(100002,
		 * "小区ID不能为空"); }
		 */

		WebServiceSession webServiceSession = this
				.getWebServiceSession(request);

		if (webServiceSession == null) {
			return this.abnormalResp(CodeConst.SYS_CODE_2001,
					InfoConst.SYS_INFO_2001);
		}

		String userId = webServiceSession.getUserID();

		// String userId = "b9d46887-2698-486e-af55-7b5f93eadd85";
		List<Map<String, Object>> mlist = new ArrayList<Map<String, Object>>();
		List<PropFeeMemberApartment> list = new ArrayList<PropFeeMemberApartment>();
		list = propFeeMemberApartmentService.selectList(null, commID, userId);

		for (PropFeeMemberApartment propFeeMemberApartment : list) {
			List<Map<String, Object>> blist = new ArrayList<Map<String, Object>>();
			blist = propAppService.selectProInfo(propFeeMemberApartment
					.getApartmentId());
			if (blist.size() == 0) {
				continue;
			}
			Map<String, Object> bmap = blist.get(0);
			List<Map<String, Object>> tlist = new ArrayList<Map<String, Object>>();
			tlist = propCollectionService.getPayBillInfoGroupForApp(
					propFeeMemberApartment.getApartmentId(), null);
			BigDecimal totalamount = BigDecimal.ZERO;
			Map<String, Object> mmap = new HashMap<String, Object>();
			Map<String, List<Map<String, Object>>> tempmap = new TreeMap<String, List<Map<String, Object>>>();
			for (Map<String, Object> map : tlist) {
				BigDecimal amount = (BigDecimal) map.get("sumamount");
				totalamount = totalamount.add(amount);
				String date = (String) map.get("date");
				if (tempmap.get(date) == null) {
					List<Map<String, Object>> templist = new ArrayList<Map<String, Object>>();
					templist.add(map);
					tempmap.put(date, templist);

				} else {
					tempmap.get(date).add(map);
				}

			}

			mmap.put(
					"apartmentinfo",
					bmap.get("comm") + "(" + bmap.get("building_name")
							+ bmap.get("unit_name") + bmap.get("apartment_num")
							+ ")");
			mmap.put("totalamount", totalamount);
			if (!(tempmap.keySet().size() == 0 || tempmap.keySet() == null)) {

				TreeSet<String> keyset = new TreeSet<String>(tempmap.keySet());
				mmap.put("range", keyset.first() + "至" + keyset.last());
			} else {
				mmap.put("range", "无");
			}
			mmap.put("apartmentid", propFeeMemberApartment.getApartmentId());
			mmap.put("commid", propFeeMemberApartment.getCommId());

			mlist.add(mmap);

		}
		return normalResp(0, 10, 1l, mlist);
	}

	@Override
	public Response deleteFeeMember(HttpServletRequest request,
			String apartmentId, String commId) throws AppBizException {
		if (StringUtils.isBlank(apartmentId)) {
			return this.abnormalResp(100002, "房屋ID不能为空");
		}

		if (StringUtils.isBlank(commId)) {
			return this.abnormalResp(100002, "小区ID不能为空");
		}

		WebServiceSession webServiceSession = this
				.getWebServiceSession(request);
		String userId = webServiceSession.getUserID();
		PropFeeMemberApartment propFeeMemberApartment = new PropFeeMemberApartment();
		propFeeMemberApartment.setApartmentId(apartmentId);
		propFeeMemberApartment.setCommId(commId);
		propFeeMemberApartment.setMemberId(userId);

		propFeeMemberApartmentService.deleteinfo(propFeeMemberApartment);

		return normalResp();
	}

	@Override
	public Response FeeHistoryListForApp(HttpServletRequest request,
			String commID, String apartmentID, String userID)
			throws AppBizException {

		if (StringUtils.isBlank(commID)) {

			return this.abnormalResp(100002, "小区ID不能为空");
		}

		if (StringUtils.isBlank(apartmentID)) {

			return this.abnormalResp(100002, "房屋id不能为空");
		}
		if (StringUtils.isBlank(userID)) {

			return this.abnormalResp(100002, "用户ID不能为空");
		}

		List<Map<String, Object>> mlist = new ArrayList<Map<String, Object>>();

		List<Map<String, Object>> blist = new ArrayList<Map<String, Object>>();

		blist = propAppService.selectProInfo(apartmentID);

		if (blist == null || blist.size() == 0) {

		}
		Map<String, Object> bmap = blist.get(0);

		List<Map<String, Object>> tlist = new ArrayList<Map<String, Object>>();
		tlist = propCollectionService.getHistoryInfoListForApp(userID,
				apartmentID, null);

		for (Map<String, Object> map : tlist) {
			Map<String, Object> mmap = new HashMap<String, Object>();

			String tscreate = map.get("tscreate").toString().replace(".0", "");
			String paymoney = map.get("pay_money").toString();
			String status = map.get("status").toString();
			String paybillId = map.get("paybill_id").toString();
			String monthrange = "?至?";
			if (map.get("monthrange") != null) {

				monthrange = map.get("monthrange").toString();
			}

			SimpleDateFormat dateFormat = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			Date now = new Date();
			Date expireTime = new Date();
			try {
				expireTime = dateFormat
						.parse(map.get("expire_time").toString());
				if (expireTime == null) {
					expireTime = new Date();
				}
			} catch (ParseException e) {
				expireTime = new Date();
				e.printStackTrace();
			}

			mmap.put(
					"apartmentinfo",
					bmap.get("comm") + "(" + bmap.get("building_name")
							+ bmap.get("unit_name") + bmap.get("apartment_num")
							+ ")");
			mmap.put("paymoney", paymoney);
			mmap.put("tscreate", tscreate);
			mmap.put("range", monthrange);
			mmap.put("paybillId", paybillId);
			mmap.put("billType", "2");
			mmap.put("apartmentid", apartmentID);
			mmap.put("commid", commID);
			mmap.put("enable", "0");
			mmap.put("topay", "0");
			if (now.after(expireTime)) {
				mmap.put("status", "账单已失效");

			} else {
				if (status != null) {

					switch (status) {
					case "0":

						mmap.put("status", "待支付");
						mmap.put("enable", "1");
						mmap.put("topay", "1");
						break;
					case "1":

						mmap.put("status", "支付中");
						mmap.put("enable", "1");
						break;
					case "2":

						mmap.put("status", "缴费成功");
						mmap.put("enable", "1");
						break;
					case "3":

						mmap.put("status", "缴费未成功");
						mmap.put("enable", "1");
						break;
					case "4":

						mmap.put("status", "账单已失效");

						break;
					case "5":

						mmap.put("status", "账单已失效");

						break;

					default:
						break;
					}
				} else {
					mmap.put("status", "待支付");
				}

			}

			mlist.add(mmap);

		}

		ContentComparator comp = new ContentComparator();
		Collections.sort(mlist, comp);

		return this.normalResp(0, 10, 1l, mlist);
	}

	@SuppressWarnings("unused")
	@Override
	public Response FeeHistoryDetailForApp(HttpServletRequest request,
			String apartmentID, String commID, String paybillId)
			throws AppBizException {
		if (StringUtils.isBlank(apartmentID)) {
			return this.abnormalResp(100002, "房屋ID不能为空");
		}
		if (StringUtils.isBlank(paybillId)) {
			return this.abnormalResp(100002, "账单ID不能为空");
		}
		if (StringUtils.isBlank(commID)) {
			return this.abnormalResp(100002, "小区ID不能为空");
		}
		List<Map<String, Object>> baseinfolist = new ArrayList<Map<String, Object>>();

		baseinfolist = propAppService.selectProInfo(apartmentID);

		if (baseinfolist.size() == 0) {
			return this.abnormalResp(100009, "房屋未开通该服务");
		}

		Map<String, Object> baseinfomap = baseinfolist.get(0);
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		list = propCollectionService.getHistoryPayBillInfoForApp(paybillId);

		List<Map<String, Object>> tlist = new ArrayList<Map<String, Object>>();
		tlist = propCollectionService.getHistoryInfoListForApp(null, null,
				paybillId);

		if (tlist.size() == 0) {
			return this.abnormalResp(100002, "缴费信息不存在");
		}
		Map<String, Object> paybillmap = tlist.get(0);

		BigDecimal totalamount = BigDecimal.ZERO;

		List<Map<String, Object>> ttlist = new ArrayList<Map<String, Object>>();

		for (Map<String, Object> map : list) {

			BigDecimal sum = (BigDecimal) map.get("sum");
			totalamount = totalamount.add(sum);
			String name = (String) map.get("name");
			String datearray = (String) map.get("datearray");
			String[] dates = datearray.split(",");
			TreeSet<String> dateset = new TreeSet<String>();
			for (int i = 0; i < dates.length; i++) {
				dateset.add(dates[i]);
			}

			Map<String, Object> ttmap = new HashMap<String, Object>();

			ttmap.put("name", name);
			ttmap.put("sum", sum);
			ttmap.put("range", dateset.first() + "至" + dateset.last());

			ttlist.add(ttmap);

		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("tscreate",
				paybillmap.get("tscreate").toString().replace(".0", ""));
		String monthrange = "";
		if (paybillmap.get("monthrange") != null) {

			monthrange = paybillmap.get("monthrange").toString();
		}
		// map.put("monthrange", monthrange);
		map.put("pay_money", paybillmap.get("pay_money").toString());
		map.put("apartmentID", apartmentID);
		map.put("payBillID", paybillId);
		map.put("commID", commID);
		Date now = new Date();
		Date expireTime = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		try {

			if (expireTime != null) {

				expireTime = dateFormat.parse(paybillmap.get("expire_time")
						.toString());
			} else {
				expireTime = new Date();
			}
		} catch (ParseException e) {
			expireTime = new Date();
			e.printStackTrace();
		}

		String status = paybillmap.get("status").toString();
		if (now.after(expireTime)) {
			map.put("status", "账单已失效");
		} else {
			if (status != null) {

				switch (status) {
				case "0":

					map.put("status", "待支付");

					break;
				case "1":

					map.put("status", "支付中");

					break;
				case "2":

					map.put("status", "缴费成功");

					break;
				case "3":

					map.put("status", "缴费未成功");

					break;
				case "4":

					map.put("status", "账单已失效");

					break;
				case "5":

					map.put("status", "账单已失效");

					break;

				default:
					break;
				}
			} else {
				map.put("status", "待支付");
			}

		}

		String building_name = (String) baseinfomap.get("building_name");
		String unit_name = (String) baseinfomap.get("unit_name");
		String apartment_num = (String) baseinfomap.get("apartment_num");
		String comm = (String) baseinfomap.get("comm");
		String fee_area = (String) baseinfomap.get("fee_area");

		List<Map<String, Object>> baseInfo = new ArrayList<Map<String, Object>>();
		if (paybillmap.get("pay_time") != null) {

			Map<String, Object> qmap5 = new HashMap<String, Object>();
			qmap5.put("name", "缴费时间");
			qmap5.put("value", StringUtils.toString(paybillmap.get("pay_time"))
					.replace(".0", ""));
			baseInfo.add(qmap5);
		}
		Map<String, Object> qmap1 = new HashMap<String, Object>();
		qmap1.put("name", "小区名称");
		qmap1.put("value", comm);
		Map<String, Object> qmap2 = new HashMap<String, Object>();
		qmap2.put("name", "房屋信息");
		qmap2.put("value", building_name + unit_name + apartment_num);
		Map<String, Object> qmap3 = new HashMap<String, Object>();
		qmap3.put("name", "房屋面积");
		qmap3.put("value", fee_area + "平");
		Map<String, Object> qmap4 = new HashMap<String, Object>();
		qmap4.put("name", "缴费期间");
		qmap4.put("value", monthrange);

		baseInfo.add(qmap1);
		baseInfo.add(qmap2);
		baseInfo.add(qmap3);
		baseInfo.add(qmap4);
		map.put("baseInfo", baseInfo);
		// map.put("comm", comm);
		// map.put("fee_area", fee_area);
		// map.put("apartmentinfo", building_name + unit_name);
		map.put("details", ttlist);

		return normalResp(map);
	}

	@Override
	public Response result(HttpServletRequest request) {
		// TODO Auto-generated method stub
		System.out.println("1");

		return Response.ok(request.getParameter("echostr").toString(),
				MediaType.TEXT_HTML).build();
	}

	@Override
	public Response getTotalFeeByApartmentID(HttpServletRequest request,
			String commID, String apartmentID) throws AppBizException {

		Map<String, Object> res = feeDetailService
				.getTotalFeeDetailByApartmentID(apartmentID);

		if (res.get("apartmentID") != null
				&& !StringUtils.isBlank(res.get("apartmentID").toString())) {
			return this.normalResp(res);
		}

		// TODO Auto-generated method stub
		return this.normalResp();
	}

	@Override
	public Response _check(HttpServletRequest request, PayBillDto payBillDto)
			throws AppBizException {

		Map<String, Object> res = feeDetailService._check(
				payBillDto.getApartmentID(), payBillDto.getFeeDetailIDs());
		// TODO Auto-generated method stub
		return this.normalResp(res);
	}
}
